package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class UserPaidTrackStrategy implements UpdateUserPaidRecordStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;
    @Transactional
    @Override
    public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        // 根据订单编号从user_paid_track表中查询数据
        LambdaQueryWrapper<UserPaidTrack> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(lambdaQueryWrapper);       // 查询满足条件的总记录数据
        if (count != 0) {
            return;
        }

        // 保存声音购买的信息
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();

        // 根据声音的id查询声音数据
        Long id = itemIdList.get(0);
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(id);
        TrackInfo trackInfo = trackInfoResult.getData();

        itemIdList.forEach(trackId -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(trackId);
            userPaidTrackMapper.insert(userPaidTrack);
        });
    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_TRACK;
    }
}
